# -*- coding: utf-8 -*-
import time
import pytest
from config.config import NOW_ENV, Current_log_path, \
    test_request_parameters, beta_request_parameters, soa_request_parameters
from core import YamlLoad
from core.Client import run_test
from core.YamlLoad import write_center_params
from utils.Mysql import db
from utils.logger import log


def clear_extract_yaml():
    """
    清除extract_yaml文件内容
    :return:
    """
    YamlLoad.clear_center_params()


def web_login():
    """
    获取pc端管理员账号，并将token插入extract_yaml文件中
    :return:
    """
    try:
        if NOW_ENV == "TEST":
            account = test_request_parameters['admin_account']
        elif NOW_ENV == "BETA":
            account = beta_request_parameters['admin_account']
        elif NOW_ENV == "SOA":
            account = soa_request_parameters['admin_account']
        else:
            log.error("环境配置错误，请检查")
            raise
        # 发送验证码
        run_time = int(time.time()-5)
        time.sleep(25)
        send_data = YamlLoad.read_file(r"DataDriven/global/send_code.yaml")
        run_test(send_data[0])
        code = 0
        for num in range(1, 10):
            result = db.get_login_code(account, 'b', run_time)
            if result['db_send_timestamp'] >= result['timestamp']:
                log.info('查询出来的验证码符合条件，使用该验证码。')
                code = result['code']
                break
            else:
                log.info('查询出来的验证码发送时间 < 接口调用时间，不采用该验证码，重新执行。')
                time.sleep(10)
                continue
        if code:
            data = YamlLoad.read_file(r"DataDriven/global/global_get_token.yaml")
            data[0]["requests"]["data"]["code"] = code
            run_test(data[0])
            # 选择机构，获取web端token
            p_data = YamlLoad.read_file(r'DataDriven/global/global_get_organization.yaml')
            login_result = run_test(p_data[0])
        else:
            login_result = False
            raise AttributeError('没有验证码')
        return login_result
    except AssertionError:
        log.error("全局前置条件执行失败..")


def app_login():
    """
    获取app端管理员账号，并将token插入extract_yaml文件中
    :return:
    """
    try:
        if NOW_ENV == "TEST":
            account = test_request_parameters['admin_account']
        elif NOW_ENV == "BETA":
            account = beta_request_parameters['admin_account']
        elif NOW_ENV == "SOA":
            account = soa_request_parameters['admin_account']
        else:
            log.error("环境配置错误，请检查")
            raise
        # 发送验证码
        run_time = int(time.time())
        time.sleep(2)
        send_data = YamlLoad.read_file(r"DataDriven/global/send_m_code.yaml")
        run_test(send_data[0])
        code = 0
        for num in range(1, 10):
            result = db.get_login_code(account, 'b', run_time)
            if result['db_send_timestamp'] >= result['timestamp']:
                code = result['code']
                break
            else:
                time.sleep(10)
                continue
        if code:
            data = YamlLoad.read_file(r"DataDriven/global/global_get_m_token.yaml")
            data[0]["requests"]["data"]["code"] = code
            run_test(data[0])
            # 选择机构，获取web端token
            p_data = YamlLoad.read_file(r'DataDriven/global/global_get_m_organization.yaml')
            login_result = run_test(p_data[0])
        else:
            login_result = False
            raise AttributeError('没有验证码')
        return login_result
    except AssertionError:
        log.error("全局前置条件执行失败..")


def C_login():
    """
    获取app端管理员账号，并将token插入extract_yaml文件中
    :return:
    """
    try:
        if NOW_ENV == "TEST":
            account = test_request_parameters['admin_account']
        elif NOW_ENV == "BETA":
            account = beta_request_parameters['admin_account']
        elif NOW_ENV == "SOA":
            account = soa_request_parameters['admin_account']
        else:
            log.error("环境配置错误，请检查")
            raise
        # 发送验证码
        run_time = int(time.time())
        time.sleep(2)
        send_data = YamlLoad.read_file(r"DataDriven/global/send_c_code.yaml")
        run_test(send_data[0])
        code = 0
        for num in range(1, 10):
            result = db.get_login_code(account, 'h5', run_time)
            if result['db_send_timestamp'] >= result['timestamp']:
                code = result['code']
                break
            else:
                time.sleep(10)
                continue
        if code:
            data = YamlLoad.read_file(r"DataDriven/global/global_get_c_token.yaml")
            data[0]["requests"]["data"]["code"] = code
            run_test(data[0])
            # 选择机构，获取web端token
            p_data = YamlLoad.read_file(r'DataDriven/global/global_get_m_organization.yaml')
            login_result = run_test(p_data[0])
        else:
            login_result = False
            raise AttributeError('没有验证码')
        return login_result
    except AssertionError:
        log.error("全局前置条件执行失败..")


def clear_current_log():
    """清除上一次的执行日志"""
    with open(Current_log_path, "w") as f:
        f.write("")
    log.info('current_log文件清除完成.')


def delete_Log():
    """删除日志文件"""
    log.delete_log_file()
    log.info("=" * 60 + "Test Closure" + "=" * 60 + "\n" * 3)


@pytest.fixture(scope="session", autouse=True)
def session_control():
    # clear_extract_yaml()
    clear_current_log()
    # login()
    yield
    delete_Log()
    # now = time.strftime('%Y-%m-%d %H:%M:%S')
    # now_hour = parse(now).hour
    # if now_hour < release_hour:
    #     pass
    # else:
    # feishu_msg.send_msg()


# if __name__ == '__main__':
    # print(web_login())
    # print(C_login())
    # print(app_login())
